package com.tyjc.unique;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;

import com.alibaba.fastjson.JSON;
import com.tyjc.unique.net.Base64;
import com.tyjc.unique.view.onTopTitleClickListener;
import com.fyzk.activity.app.App;
import com.fyzk.activity.app.AppToast;
import com.fyzk.bean.StringResultBean_New;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.DJ_ProgressDialog;
import com.fyzk.net.PublicMethod;
import com.fyzk.net.ToolsAesCrypt;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.LogUtil;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.UnsupportedEncodingException;

import com.wf.domain.UrlDef;
import http.XRequestCallBack;

/**
 * 基础Activity
 */
public class AnaylaseBaseActivity extends AppCompatActivity implements
        OnClickListener, onTopTitleClickListener {

    protected final String TAG = this.getClass().getSimpleName();
    protected Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            parserMessage(msg);
        }
    };

    protected void parserMessage(Message msg) {
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
    }


    @Override
    protected void onStop() {
        // int version = Integer.valueOf(android.os.Build.VERSION.SDK);
        // if (version >= 5) {
        // overridePendingTransition(R.anim.activity_translate_in,
        // R.anim.activity_translate_out);
        // }
        super.onStop();

    }

    protected void init() {
    }



    private void showProgressDialog() {
        DJ_ProgressDialog.show(getContext(), "正在登陆，请稍后...",
                false, true);
    }

    private void cancelProgressDialog() {
        DJ_ProgressDialog.dissmiss();
    }


    /**
     * post请求
     *
     * @param requestCode
     * @param params
     * @param showProgress 是否显示加载提示
     */
    public void httpPostJson(int requestCode, String command, JSONObject params,
                             boolean showProgress) {
        sendRequestUseJson(HttpMethod.POST, requestCode, command, params, showProgress);
    }


    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param method
     * @param params2
     * @param showProgress
     */
    public void sendRequestUseJson(HttpMethod method, int requestCode, String command,
                                   JSONObject params2, final boolean showProgress) {


        if (!AppUtil.isNetworkAvailable(this)) {
            AppToast.getToast().show("网络错误!");
            return;
        }

        if (showProgress) {
            showProgressDialog();
        }

        XRequestCallBack<String> callBack = new XRequestCallBack<String>(
                requestCode) {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                LogUtil.d("联网失败:" + ex.getMessage());
                AnaylaseBaseActivity.this.onFailure(getRequestCode(), null);
                if (showProgress) {
                    cancelProgressDialog();
                }
            }

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                String netResult = null;
                String decode_ = null;
                LogUtil.d("联网返回成功:" + result);
                try {
                    decode_ = ToolsAesCrypt.Decrypt(result.substring(1, result.length() - 1),
                            UrlDef.stringFromJNI());
                    System.out.println("decode>" + decode_);
                    byte[] base64d = Base64.decode(decode_);
                    byte[] decompress = PublicMethod.decompress2(base64d);
                    netResult = new String(decompress, "utf-8");

                    LogUtil.d("联网：解密后返回>" + netResult.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    StringResultBean_New resultBean = JSON.parseObject(netResult,
                            StringResultBean_New.class);
                    if (resultBean.getErrorcode().equals("0")) {
                        AnaylaseBaseActivity.this.onSuccess(getRequestCode(), resultBean,
                                netResult);
                    } else if(resultBean.getErrorcode().equals("110003")) {
                        MySharedPreferences.getInstance().setAuthToken("");
                        MySharedPreferences.getInstance().setLoginStatus(false);
                        AnaylaseBaseActivity.this.onFailure(getRequestCode(), resultBean.getMsg());
                    } else {
                        AnaylaseBaseActivity.this.onFailure(getRequestCode(), resultBean.getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtil.d("AnaylaseBaseActivity >>  result 数据异常。。");
                    AnaylaseBaseActivity.this.onFailure(getRequestCode(), e.getMessage());
                }
                if (showProgress) {
                    cancelProgressDialog();
                }

            }
        };

        RequestParams params = new RequestParams(UrlDef.TY_URL_NEW_DATA);
        //打印请求
        try {
            JSONObject requstJson = new JSONObject();

            JSONObject clientInfo = new JSONObject();
            long timestamp = System.currentTimeMillis();


            String token = http.DataUtil.md5.MD5.toMd5(http.DataUtil.md5.MD5.toMd5((UrlDef.stringFromJNI() +
                    timestamp).getBytes()).getBytes());
            String agent = "360zhushou";
//            try {
//                ApplicationInfo appInfo = App.getContext().getPackageManager().getApplicationInfo(
//                        App.getContext().getPackageName(), PackageManager.GET_META_DATA);
//                agent = "";
//            } catch (PackageManager.NameNotFoundException e1) {
//                agent = "gw";
//                e1.printStackTrace();
//            }
            clientInfo.put("agentId", agent);
            clientInfo.put("apn", "WIFI");
            clientInfo.put("authtoken", MySharedPreferences.getInstance().getAuthtoken());
            clientInfo.put("model", "android");
            clientInfo.put("timestamp", timestamp);
            clientInfo.put("token", token);
            clientInfo.put("version", App.getVersionCode());
            requstJson.put("clientInfo", clientInfo);
            requstJson.put("command", command);
            requstJson.put("data", params2);
            LogUtil.d("联网：加密前请求>" + requstJson.toString());
            String encrypt = ToolsAesCrypt.Encrypt(requstJson.toString(), UrlDef.stringFromJNI());
            LogUtil.d("联网：发送请求>" + encrypt);
            params.addBodyParameter("body", encrypt);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d("加密失败");
        }

        LogUtil.v("联网请求：" + params);
        if (method == HttpMethod.POST) {
            x.http().post(params, callBack);
        } else if (method == HttpMethod.GET) {
            x.http().get(params, callBack);
        } else {
            x.http().post(params, callBack);
        }

    }
//
//    protected void onSuccess(int requestCode,
//                             StringResultBean resultBean, String result) {
//
//    }
//
//
//    protected void onFailure(int requestCode, Object o) {
//
//    }


    protected void onSuccess(int requestCode, StringResultBean_New resultBean, String
            result) {
    }

    protected void onFailure(int requestCode, String msg) {
    }

    /**
     * 填写请求字段
     *
     * @param schemaDef
     */
    protected void request(int schemaDef) {
    }

    ;

    public Context getContext() {
        return this;
    }

    @Override
    public void onClick(View arg0) {

    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onCenterClick() {

    }

    @Override
    public void onRightClick() {

    }


    public void startActivity(Class activity) {
        Intent intent = new Intent(this, activity);
        startActivity(intent);
    }

    public void showToast(String msg) {
        AppToast.getToast().show(msg);
    }

    public void showToast(int msg) {
        AppToast.getToast().show(msg);
    }


}
